"""


"""
from flask import current_app
from flask import g, jsonify
from flask import redirect
from flask import request
from flask import session

from info import constants
from info import db
from info.models import News, Category
from info.utils.common import user_login_data
from info.utils.qiniu_storage import storage
from info.utils.response_code import RET
from . import profile_blu
from flask import render_template


@profile_blu.route("/info")
@user_login_data
def info():
    """
    处理  渲染个人中心页面的  请求
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")

    data = {
        "user_info": user.to_dict() if user else None
    }
    return render_template("news/user.html", data=data)


@profile_blu.route("/base_info", methods=["POST", "GET"])
@user_login_data
def base_info():
    user = g.user
    if not user:
        return redirect("/")

    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("news/user_base_info.html", data=data)
    """
    1,获取参数
    2,判空校验
    3,保存到数据库
        # 如果session中有这些数据的话,也要更新session
    4,返回操作结果
    """
    # 1,获取参数
    data_dict = request.json
    signature = data_dict.get("signature")
    nick_name = data_dict.get("nick_name")
    gender = data_dict.get("gender")
    # 2,判空校验
    if not all([signature, nick_name, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if gender not in ("MAN", "WOMAN"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 3,保存到数据库
    user.signature = signature
    user.nick_name = nick_name
    user.gender = gender
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg="数据库操作失败")
    # 如果session中有这些数据的话,也要更新session
    session["nick_name"] = nick_name
    # 4,返回操作结果
    return jsonify(errno=RET.OK, errmsg="保存成功")


@profile_blu.route("/pic_info", methods=["POST", "GET"])
@user_login_data
def pic_info():
    user = g.user
    if not user:
        return redirect("/")

    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("news/user_pic_info.html", data=data)

    """
    1,获取参数(头像图片)
    2,上传图片到七牛云 ,并且要拿到返回值
    3,保存数据到数据库
    4,返回操作结果
    """
    # 1,获取参数(头像图片)
    try:
        image_file = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数错误")

    # 2,上传图片到七牛云 ,并且要拿到返回值
    try:
        url = storage(image_file)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="上传头像失败")

    # 3,保存数据到数据库
    user.avatar_url = url
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")

    # 4,返回操作结果
    data={
        "avatar_url": constants.QINIU_DOMIN_PREFIX + user.avatar_url
    }
    return jsonify(errno=RET.OK,errmsg="上传成功", data=data)


@profile_blu.route("/pass_info", methods=["POST", "GET"])
@user_login_data
def pass_info():
    user = g.user
    if not user:
        return redirect("/")

    if request.method == "GET":
        data = {
            "user_info": user.to_dict() if user else None
        }
        return render_template("news/user_pass_info.html", data=data)

    """
    1,获取参数
    2,判空校验
    3,保存数据
    4,返回操作结果
    """

    # 1,获取参数
    data_dict = request.json
    old_password = data_dict.get("old_password")
    new_password = data_dict.get("new_password")
    new_password2 = data_dict.get("new_password2")
    # 2,判空校验
    if not all([old_password, new_password, new_password2]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if new_password != new_password2:
        return jsonify(errno=RET.PARAMERR,errmsg="两次密码不一致")
    if not user.check_passowrd(old_password):
        return jsonify(errno=RET.PARAMERR,errmsg="旧密码错误")
    # 3,保存数据
    user.password = new_password
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")

    # 4,返回操作结果
    return jsonify(errno=RET.OK, errmsg="修改成功")


@profile_blu.route("/collection")
@user_login_data
def collection():
    user = g.user
    if not user:
        return redirect("/")

    """
    1,获取参数 p  校验
    2,查询数据库, 查询user收藏的新闻   分页查询 paginate()
    3,把当前页的数据 paginate.items 转换成字典
    4,返回操作结果
    """

    # 1,获取参数 p  校验
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 2,查询数据库, 查询user收藏的新闻   分页查询 paginate()
    cur_page_news = []
    try:
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        cur_page_news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 3,把当前页的数据 paginate.items 转换成字典
    cur_page_news_list = []
    for i in cur_page_news:
        cur_page_news_list.append(i.to_dict())

    # 4,返回操作结果
    data = {
        "cur_page_news_list": cur_page_news_list,
        "current_page":current_page,
        "total_page":total_page
    }
    return render_template("news/user_collection.html", data=data)


@profile_blu.route("/news_list")
@user_login_data
def news_list():
    user = g.user
    if not user:
        return redirect("/")

    """
    1,获取参数 p  校验
    2,查询数据库, 查询user收藏的新闻   分页查询 paginate()
    3,把当前页的数据 paginate.items 转换成字典
    4,返回操作结果
    """

    # 1,获取参数 p  校验
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    # 2,查询数据库, 查询user收藏的新闻   分页查询 paginate()
    cur_page_news = []
    try:
        paginate = user.news_list.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        cur_page_news = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 3,把当前页的数据 paginate.items 转换成字典
    cur_page_news_list = []
    for i in cur_page_news:
        cur_page_news_list.append(i.to_review_dict())

    # 4,返回操作结果
    data = {
        "cur_page_news_list": cur_page_news_list,
        "current_page":current_page,
        "total_page":total_page
    }
    return render_template("news/user_news_list.html", data=data)


@profile_blu.route("/news_release", methods=["POST", "GET"])
@user_login_data
def news_release():
    user = g.user
    if not user:
        return redirect("/")

    if request.method == "GET":
        # 查询数据库, 查询分类表,要把所有分类传到模板
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

        data = {
            "user_info": user.to_dict() if user else None,
            "categories": categories
        }
        return render_template("news/user_news_release.html", data=data)

    """
    1, 获取参数,判空
    2, 上传图片到七牛云
    3, 创建News模型对象,  并且设置属性
    4, 添加,提交数据
    5, 返回操作结果
    """

    # 1, 获取参数,判空
    data_dict = request.form
    title = data_dict.get("title")
    category_id = data_dict.get("category_id")
    digest = data_dict.get("digest")
    index_image = request.files.get("index_image")
    content = data_dict.get("content")
    source = "个人发布"

    if not all([title, category_id, digest, index_image, content, source]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 2, 上传图片到七牛云
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)

    try:
        index_image_filename = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)

    # 3, 创建News模型对象,  并且设置属性
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + index_image_filename
    news.content = content
    # 新闻来源
    news.source = source
    # 设置新闻的作者的id
    news.user_id = user.id
    # 设置新闻的状态为审核中
    news.status = 1
    # 4, 添加,提交数据
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="发布失败")

    # 5, 返回操作结果
    return jsonify(errno=RET.OK,errmsg="发布成功, 待审核")